//
//  WDTabBarController.m
//  winterTest
//
//  Created by wd on 15/10/26.
//  Copyright © 2015年 wd ,Ltd. All rights reserved.
//

#import "WDTabBarController.h"
#import <objc/runtime.h>
#import "WDTabBar.h"
#import "WDNavigationController.h"

#import "WDLifeStyleViewController.h"
#import "WDMySubscribeViewController.h"
#import "WDDiscoverViewController.h"
#import "WDMoreViewController.h"

#import "WDTestViewController.h"

NSUInteger WDTabBarItemsCount = 0;

@interface UIViewController (WDTabBarControllerItemInternal)

- (void)wd_setTabBarController:(WDTabBarController *)tabBarController;

@end

@interface WDTabBarController ()<UITabBarControllerDelegate>

@end

@implementation WDTabBarController
@synthesize viewControllers = _viewControllers;

#pragma mark - 
#pragma mark - life cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 设置tabBarItem 属性
    [self setUpTabBarItemTextAttributes];
    [self setUpTabBar];
    [self setUpViewControllers];
    self.delegate = self;
    
    [[UITabBar appearance] setBackgroundImage:[self imageWithColor:[UIColor whiteColor]]];
    // 去除 TabBar 自带顶部阴影
//    [[UITabBar appearance] setShadowImage:[[UIImage alloc]init]];
}

#pragma mark -
#pragma mark - setUI method

- (void)setUpViewControllers
{
    WDLifeStyleViewController *lifeStyleVC = [[WDLifeStyleViewController alloc]init];
    UIViewController *navVC1 = [[WDNavigationController alloc]initWithRootViewController:lifeStyleVC];
    
    WDMySubscribeViewController *mySubscribeVC = [[WDMySubscribeViewController alloc]init];
    UIViewController *navVC2 = [[WDNavigationController alloc]initWithRootViewController:mySubscribeVC];
    
    WDDiscoverViewController *discoverleVC = [[WDDiscoverViewController alloc]init];
    UIViewController *navVC3 = [[WDNavigationController alloc]initWithRootViewController:discoverleVC];
    
    WDMoreViewController *moreVC = [[WDMoreViewController alloc]init];
    UIViewController *navVC4 = [[WDNavigationController alloc]initWithRootViewController:moreVC];
    
    [self customizeTabBarForController];
    [self setViewControllers:@[
                               navVC1,
                               navVC2,
                               navVC3,
                               navVC4
                               ]];
}

- (void)customizeTabBarForController
{
    NSDictionary *dic1 = @{
                           WDTabBarItemTitle : @"生活圈",
                           WDTabBarItemImage : @"tabbar_icon_livearea28x28",
                           WDTabBarItemSelectedImage : @"tabbar_icon_sleect_livearea28x28"
                           };
    NSDictionary *dic2 = @{
                           WDTabBarItemTitle : @"我的订阅",
                           WDTabBarItemImage : @"tabbar_icon_subscription28x28",
                           WDTabBarItemSelectedImage : @"tabbar_icon_select_subscription28x28"
                           };
    NSDictionary *dic3 = @{
                           WDTabBarItemTitle : @"发现",
                           WDTabBarItemImage : @"tabbar_icon_more28x28",
                           WDTabBarItemSelectedImage : @"tabbar_icon_select_more28x28"
                           };
    NSDictionary *dic4 = @{
                           WDTabBarItemTitle : @"更多",
                           WDTabBarItemImage : @"tabbar_icon_more28x28",
                           WDTabBarItemSelectedImage : @"tabbar_icon_select_more28x28"
                           };
    NSArray *tabBarItemAttributes = @[
                                      dic1,
                                      dic2,
                                      dic3,
                                      dic4];
    self.tabBarItemsAttrobutes = tabBarItemAttributes;
}

/** 将系统的tabbar 替换成自定义的 */
- (void)setUpTabBar
{
    [self setValue:[[WDTabBar alloc]init] forKey:@"tabBar"];
}

/**
 *  tabBarItem 的选中和默认的文字属性
 */
- (void)setUpTabBarItemTextAttributes
{
    // default
    NSMutableDictionary *normalAttrs = [NSMutableDictionary dictionary];
    normalAttrs[NSForegroundColorAttributeName] = [UIColor grayColor];
    
    // selected
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    selectedAttrs[NSForegroundColorAttributeName] = [UIColor orangeColor];
    
    // 文字属性
    UITabBarItem *tabBar = [UITabBarItem appearance];
    [tabBar setTitleTextAttributes:normalAttrs forState:UIControlStateNormal];
    [tabBar setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
}

- (void)setViewControllers:(NSArray *)viewControllers
{
    if (_viewControllers && _viewControllers.count) {
        for (UIViewController *viewController in _viewControllers) {
            [viewController willMoveToParentViewController:nil];
            [viewController.view removeFromSuperview];
            [viewController removeFromParentViewController];
        }
    }
    
    if (viewControllers && [viewControllers isKindOfClass:[NSArray class]]) {
        _viewControllers = [viewControllers copy];
        if (_tabBarItemsAttrobutes) {
            if (_tabBarItemsAttrobutes.count != _viewControllers.count) {
                [NSException raise:@"WDTabBarController" format:@"设置_tabBarItemsAttributes属性时，请确保元素个数与控制器的个数相同，并在方法`-setViewControllers:`之前设置"];
            }
        }
        WDTabBarItemsCount = [viewControllers count];
        NSUInteger idx = 0;
        for (UIViewController *viewController in viewControllers) {
            [self addOneChildViewController:viewController
                                  withTitle:_tabBarItemsAttrobutes[idx][WDTabBarItemTitle]
                            normalImageName:_tabBarItemsAttrobutes[idx][WDTabBarItemImage]
                          selectedImageName:_tabBarItemsAttrobutes[idx][WDTabBarItemSelectedImage]];
            [viewController wd_setTabBarController:self];
            idx++;
        }
    } else {
        for (UIViewController *viewController in _viewControllers) {
            [viewController wd_setTabBarController:nil];
        }
        _viewControllers = nil;
    }
}

/**
 *  添加一个字控制器
 *
 *  @param viewController    控制器
 *  @param title             标题
 *  @param normalImageName   默认图片
 *  @param selectedImageName 选中图片
 */
- (void)addOneChildViewController:(UIViewController *)viewController
                        withTitle:(NSString *)title
                 normalImageName:(NSString *)normalImageName
                selectedImageName:(NSString *)selectedImageName
{
    viewController.tabBarItem.title = title;
    
    UIImage *normalImage = [UIImage imageNamed:normalImageName];
    normalImage = [normalImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    viewController.tabBarItem.image = normalImage;
    
    UIImage *selectedImage = [UIImage imageNamed:selectedImageName];
    selectedImage = [selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    viewController.tabBarItem.selectedImage = selectedImage;
    
    [self addChildViewController:viewController];
}

//这个方法可以抽取到 UIImage 的分类中
- (UIImage *)imageWithColor:(UIColor *)color
{
    NSParameterAssert(color != nil);
    
    CGRect rect = CGRectMake(0, 0, 1, 1);
    // Create a 1 by 1 pixel context
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    [color setFill];
    UIRectFill(rect);   // Fill it with your color
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark -
#pragma mark - TabBarController delegate

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *nav = (UINavigationController *)viewController;
        if ([nav.topViewController isKindOfClass:[WDMoreViewController class]]) {
            
//            NSInteger selectedIndex = [tabBarController.viewControllers indexOfObject:viewController];
            
            WDTestViewController *VC = [[WDTestViewController alloc] init];
            VC.showVC_Type = TestShowVC_Type_Modal;
            WDNavigationController *nav = [[WDNavigationController alloc] initWithRootViewController:VC];
            [tabBarController presentViewController:nav animated:YES completion:nil];
            VC.cancleActionBlock = ^(BOOL success){
                if (success) {
//                    tabBarController.selectedIndex = selectedIndex;
                }
            };
            return NO;
        }
    }
    return YES;
}

@end

#pragma mark -
#pragma mark - UIViewController+WDTabBarControllerItem

@implementation UIViewController (WDTabBarControllerItemInternal)

- (void)wd_setTabBarController:(WDTabBarController *)tabBarController
{
    objc_setAssociatedObject(self, @selector(wd_tabBarController), tabBarController, OBJC_ASSOCIATION_ASSIGN);
}

@end

@implementation UIViewController (WDTabBarController)

- (WDTabBarController *)wd_tabBarController
{
    WDTabBarController *tabBarController = objc_getAssociatedObject(self, @selector(wd_tabBarController));
    if (!tabBarController && self.parentViewController) {
        tabBarController = [self.parentViewController wd_tabBarController];
    }
    return tabBarController;
}

@end